package com.dashu.base.utils.File;

import com.dashu.base.utils.encryption.Base64;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.channels.FileChannel;

public class PicUtils {

    /**
     * 图片转base64
     *
     * @param path
     * @return
     */
    public static String picTobase64(String path) {
        InputStream inputStream;
        byte[] data;
        try {
            inputStream = new FileInputStream(path);
            data = new byte[inputStream.available()];
            inputStream.read(data);
            inputStream.close();
            BASE64Encoder base64Encoder = new BASE64Encoder();
            return base64Encoder.encode(data).replaceAll("[\\s*\t\n\r]", "");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * base64转图片
     *
     * @param path
     * @return
     */
    public static boolean base64Topic(String path, String imgStr) {
        if (imgStr == null) {
            return false;
        } else {
            BASE64Decoder decoder = new BASE64Decoder();

            try {
                byte[] b = decoder.decodeBuffer(imgStr);

                for (int i = 0; i < b.length; ++i) {
                    if (b[i] < 0) {
                        b[i] = (byte) (b[i] + 256);
                    }
                }

                OutputStream out = new FileOutputStream(path);
                out.write(b);
                out.flush();
                out.close();
                return true;
            } catch (Exception var5) {
                return false;
            }
        }
    }

    /**
     * 通过图片的url获取图片的base64字符串
     *
     * @param imgUrl 图片url
     * @return 返回图片base64的字符串
     */

    public static String image2Base64(String imgUrl) throws Exception {
        // new一个URL对象
        URL url = new URL(imgUrl);
        // 打开链接
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        // 设置请求方式为"GET"
        conn.setRequestMethod("GET");
        // 超时响应时间为5秒
        conn.setConnectTimeout(5 * 1000);
        // 通过输入流获取图片数据
        InputStream inStream = conn.getInputStream();
        // 得到图片的二进制数据，以二进制封装得到数据，具有通用性
        byte[] data = readInputStream(inStream);
        BASE64Encoder base64Encoder = new BASE64Encoder();
        String s = base64Encoder.encode(data).replaceAll("[\\s*\t\n\r]", "");
        return s;

    }

    private static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        // 创建一个Buffer字符串
        byte[] buffer = new byte[1024];
        // 每次读取的字符串长度，如果为-1，代表全部读取完毕
        int len = 0;
        // 使用一个输入流从buffer里把数据读取出来
        while ((len = inStream.read(buffer)) != -1) {
            // 用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
            outStream.write(buffer, 0, len);
        }
        // 关闭输入流
        inStream.close();
        // 把outStream里的数据写入内存
        return outStream.toByteArray();
    }



    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        resizeImage("C:\\Users\\Administrator\\Desktop\\微信图片_20200427112951.jpg" , "C:\\Users\\Administrator\\Desktop\\微信图片_20200427112951.jpg" , 960 , 960);
        System.out.println((System.currentTimeMillis() - start) / 1000);
    }


    /***
          * 等比例改变图片像素
          * 
          * @param srcImgPath   原路径
          * @param distImgPath  生成路径
          * @param w  h 宽高
          * @throws IOException
          */
    public static void resizeImage(String srcImgPath, String distImgPath, int w , int h) {
        File srcFile = new File(srcImgPath);
        Image srcImg = null;
        try {
            srcImg = ImageIO.read(srcFile);
            int[] w_h = getImgW_H(srcImgPath);
            int w_new = 0, h_new = 0;
            if (w_h[0] > w_h[1]){
                w_new = w;
                h_new = (int)((double)w_h[1] / (double) w_h[0] * h);
            } else {
                h_new = h;
                w_new = (int)((double)w_h[0] / (double) w_h[1] * w);
            }
            if (w_h[0] <= w && w_h[1] <= w)
                return;

            BufferedImage buffImg = null;
            buffImg = new BufferedImage(w_new, h_new, BufferedImage.TYPE_INT_RGB);
            buffImg.getGraphics().drawImage(srcImg.getScaledInstance(w_new, h_new, Image.SCALE_SMOOTH), 0, 0, null);
//            try {
//                Thread.sleep(3000);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
            ImageIO.write(buffImg, "JPEG", new File(distImgPath));
            buffImg.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    /**
     *      * 获取图片的真实像素
     *      * 
     *      * @param imgPath
     *      * @return
     *     
     */
    @SuppressWarnings({"hiding", "unused"})
    public static int[] getImgW_H(String imgPath) {
        File file = new File(imgPath);
        FileChannel fc = null;
        if (file.exists() && file.isFile()) {
            try {
                @SuppressWarnings("resource")
                FileInputStream fs = new FileInputStream(file);
                fc = fs.getChannel();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
        int[] result = new int[2];
        try {
            BufferedImage bi = ImageIO.read(file);
            int width = bi.getWidth();
            int height = bi.getHeight();
            result[0] = width;
            result[1] = height;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            return result;
        }
    }
}
